# frozen_string_literal: true

require 'rest-client'
require 'json'
require_relative './unit'

# scheduler client class
class SchedulerClient
  def initialize(host = '172.17.0.1', port = 3000)
    @host = host
    @port = port
    url_prefix
    @url_prefix = "#{@url_prefix}#{@host}:#{@port}"
  end

  def submit_job(job_json)
    resource = RestClient::Resource.new("#{@url_prefix}/submit_job", timeout: 120)
    resource.post(job_json)
  rescue Errno::ECONNREFUSED => e
    puts e.to_s
    exit(1)
  rescue RestClient::ExceptionWithResponse => e
    e.response
  end

  def cancel_job(job_id, content)
    resource = RestClient::Resource.new("#{@url_prefix}/scheduler/v1/jobs/#{job_id}/cancel")
    resource.post(content, content_type: :json)
  rescue RestClient::ExceptionWithResponse => e
    { code: e.http_code, message: e.response }
  end

  def renew_deadline(job_id, time)
    resource = RestClient::Resource.new(
      "#{@url_prefix}/scheduler/v1/jobs/update?job_id=#{job_id}&renew_seconds=#{to_seconds(time)}")
    resource.post
  end

  def get_deadline(job_id)
    resource = RestClient::Resource.new(
      "#{@url_prefix}/scheduler/v1/jobs/#{job_id}?fields=deadline_utc")
    resource.get
  end

  def wait_jobs_once(expected_jobs)
    url = "#{@url_prefix}/scheduler/v1/jobs/wait"
    response = RestClient.post(url, expected_jobs.to_json, { content_type: :json })
    JSON.parse(response.body)
  end

  def wait_jobs_loop(initial_jobs)
    current_jobs = initial_jobs.dup
    final_response = {}

    loop do
      response = wait_jobs_once(current_jobs)
      final_response = response

      remaining_wait_on = response.fetch('wait_on', {})
      break if remaining_wait_on.empty?

      # Update for next iteration
      current_jobs['wait_on'] = remaining_wait_on
    end

    final_response
  end

  private def url_prefix
    if @host.match('.*.svc.cluster.local.*')
      # cluster use http
      @url_prefix = 'http://'
    elsif @host.match('.*[a-zA-Z]+.*')
      # Internet users should use domain name and https
      @url_prefix = 'https://'
    else
      # used in intranet for now
      @url_prefix = 'http://'
    end
  end

end

class DataApiClient < SchedulerClient
  def es_search(index, request_json)
    resource = RestClient::Resource.new("#{@url_prefix}/data_api/es/#{index}/_search")
    resource.post(request_json)
  end

  def es_opendistro_sql(request_json)
    resource = RestClient::Resource.new("#{@url_prefix}/data_api/_opendistro/_sql")
    resource.post(request_json)
  end

  def manticore_select(request_json)
    resource = RestClient::Resource.new("#{@url_prefix}/data_api/manticore/select")
    resource.post(request_json)
  end
end
